//
//  AppDelegate+ConfigTabbar.m
//  MyTabbarDemo
//
//  Created by Yuki on 2021/11/19.
//

#import "AppDelegate+ConfigTabbar.h"
#import "TZL_NavigationController.h"
#import "TZL_HomeController.h"
#import "TZL_MineController.h"
#import "TZL_PlusButton.h"
#import "UIImage+Create.h"
@interface AppDelegate ()<UITabBarControllerDelegate>
@end
@implementation AppDelegate (ConfigTabbar)
/// 配置tabbar
- (void)zl_configTabbr{
    [TZL_PlusButton registerPlusButton];//注册中间发布按钮
    //配置tabbar
    CYLTabBarController *tabBarC = [CYLTabBarController tabBarControllerWithViewControllers:[self viewControllers] tabBarItemsAttributes:[self tabbarItemsAttributes] imageInsets:UIEdgeInsetsMake(-4, 0, 0, 0) titlePositionAdjustment:UIOffsetMake(0, -8)];
    tabBarC.delegate = self;
    
    [self customizeTabBarAppearance:tabBarC];
    
    //这里的frame要和 CYLTabBarController.m的89行自己修改的部分的frame保持一致
    self.window.rootViewController = tabBarC;
}


/// 控制器
- (NSArray *)viewControllers{
    //首页
    TZL_HomeController *home_vc = [[TZL_HomeController alloc]init];
    TZL_NavigationController *home_nav = [[TZL_NavigationController alloc]initWithRootViewController:home_vc];
    [home_vc cyl_setNavigationBarHidden:YES];
    
    //我的
    TZL_MineController *mine_vc = [[TZL_MineController alloc]init];
    TZL_NavigationController *mine_nav = [[TZL_NavigationController alloc] initWithRootViewController:mine_vc];
    
    //首页
    TZL_HomeController *home_vc2 = [[TZL_HomeController alloc]init];
    TZL_NavigationController *home_nav2 = [[TZL_NavigationController alloc]initWithRootViewController:home_vc2];
    [home_vc cyl_setNavigationBarHidden:YES];
    
    //我的
    TZL_MineController *mine_vc2 = [[TZL_MineController alloc]init];
    TZL_NavigationController *mine_nav2 = [[TZL_NavigationController alloc] initWithRootViewController:mine_vc2];
    
    return @[home_nav,mine_nav,home_nav2,mine_nav2];
}
/// item基本属性
- (NSArray *)tabbarItemsAttributes{
    NSDictionary *homeDic = @{
        CYLTabBarItemTitle :@"首页",
        CYLTabBarItemImage :@"tab_icon01a",
        CYLTabBarItemSelectedImage :@"tab_icon01b",
    };
    NSDictionary *mineDic = @{
        CYLTabBarItemTitle :@"我的",
        CYLTabBarItemImage :@"tab_icon04a",
        CYLTabBarItemSelectedImage :@"tab_icon04b"
    };
    return  @[homeDic,mineDic,homeDic,mineDic];
}

/// 配置tabbar的其他属性
/// @param tabBarC 待配置的tabbar
- (void)customizeTabBarAppearance:(CYLTabBarController *)tabBarC{
    [[UITabBar appearance] setBackgroundImage:[UIImage imageWithColor:ColorHex(0x333333, 1)]];
    [tabBarC hideTabBarShadowImageView];
    [tabBarC setTintColor:UIColor.blackColor];//设置主题色
    tabBarC.tabBarHeight = 55.0f;//tabbar的高度
    tabBarC.tabBar.layer.cornerRadius = 55.0f/2.0f; //切圆角
    tabBarC.tabBar.layer.masksToBounds = YES;
    //普通状态下的文字
    NSMutableDictionary *normalDic = [NSMutableDictionary new];
    normalDic[NSForegroundColorAttributeName] = ColorHex(0x787C8C, 1);
    normalDic[NSFontAttributeName] = [UIFont systemFontOfSize:10 weight:UIFontWeightMedium];
    //选中状态下的的文字
    NSMutableDictionary *selDic = [NSMutableDictionary new];
    selDic[NSForegroundColorAttributeName] = ColorHex(0xffffff, 1);
    selDic[NSFontAttributeName] = [UIFont systemFontOfSize:10 weight:UIFontWeightMedium];
    
    UITabBarItem *tabBar = [UITabBarItem appearance];
    [tabBar setTitleTextAttributes:normalDic forState:UIControlStateNormal];
    [tabBar setTitleTextAttributes:selDic forState:UIControlStateSelected];

   
}
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
    // 确保 PlusButton 的选中状态
    [[self cyl_tabBarController] updateSelectionStatusIfNeededForTabBarController:tabBarController shouldSelectViewController:viewController];
    return YES;
}

- (void)tabBarController:(UITabBarController *)tabBarController didSelectControl:(UIControl *)control {
    UIView *animationView;
    NSLog(@"🔴\n 类名与方法名：%@，\n 第 %@ 行，\n description : %@，\n tabBarChildViewControllerIndex: %@， tabBarItemVisibleIndex : %@", @(__PRETTY_FUNCTION__), @(__LINE__), control, @(control.cyl_tabBarChildViewControllerIndex), @(control.cyl_tabBarItemVisibleIndex));
    
    // 即使 PlusButton 也添加了点击事件，点击 PlusButton 后也会触发该代理方法。
    if ([control cyl_isPlusButton]) {
        UIButton *button = CYLExternPlusButton;
        animationView = button.imageView;
        // 为加号按钮添加「缩放动画」
        [self addScaleAnimationOnView:animationView repeatCount:1];
    } else if ([control isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
        for (UIView *subView in control.subviews) {
            if ([subView isKindOfClass:NSClassFromString(@"UITabBarSwappableImageView")]) {
                animationView = subView;
                // 为其他按钮添加「旋转动画」
                [self addRotateAnimationOnView:animationView];
            }
        }
    }
}
/// 缩放动画
- (void)addScaleAnimationOnView:(UIView *)animationView repeatCount:(float)repeatCount {
    //需要实现的帧动画，这里根据需求自定义
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];
    animation.keyPath = @"transform.scale";
     animation.values = @[@1.0,@1.3,@0.9,@1.15,@0.95,@1.02,@1.0];
    animation.duration = 0.5;
    animation.repeatCount = repeatCount;
    animation.calculationMode = kCAAnimationCubic;
    [animationView.layer addAnimation:animation forKey:nil];
}

/// 旋转动画
- (void)addRotateAnimationOnView:(UIView *)animationView {
   [UIView animateWithDuration:0.32 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
       animationView.layer.transform = CATransform3DMakeRotation(M_PI, 0, 1, 0);
   } completion:nil];
   
   dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
       [UIView animateWithDuration:0.70 delay:0 usingSpringWithDamping:1 initialSpringVelocity:0.2 options:UIViewAnimationOptionCurveEaseOut animations:^{
           animationView.layer.transform = CATransform3DMakeRotation(2 * M_PI, 0, 1, 0);
       } completion:nil];
   });
}

/// 这里用了消息转发机制，在tzl_PlusButton里面转发的
- (void)didClickPlusBtn{
//    NSLog(@"-------这里实现了%@",NSStringFromClass(self.tabBarController.selectedViewController.class));
    //这里不能调用self，这里的self是TZL_PlusButton
    
    UIViewController *result = nil;
    // 获取默认的window
    UIWindow * window = [UIApplication sharedApplication].delegate.window;
    // app默认windowLevel是UIWindowLevelNormal，如果不是，找到它。
    if (window.windowLevel != UIWindowLevelNormal) {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows) {
            if (tmpWin.windowLevel == UIWindowLevelNormal) {
                window = tmpWin;
                break;
            }
        }
    }
    // 获取window的rootViewController
    result = window.rootViewController;
    while (result.presentedViewController) {
        result = result.presentedViewController;
    }
    if ([result isKindOfClass:[UITabBarController class]]) {
        result = [(UITabBarController *)result selectedViewController];
    }
    if ([result isKindOfClass:[UINavigationController class]]) {
        result = [(UINavigationController *)result visibleViewController];
    }
    
    NSLog(@"tzl_tabbarcontroller:%@",NSStringFromClass(result.class));
}
@end
